package com.kanshu.ksgb.fastread.doudou.common.versioncheck;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.SeekBar;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.google.gson.Gson;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;

import java.lang.ref.WeakReference;

import retrofit2.Call;

/**
 * 版本更新管理器
 * Created by wcy on 2017\5\17 0017.
 */
public class VersionUpdateManager {
    private static VersionUpdateManager sVersionUpdateManager;
    private VersionService mVersionService;
    private WeakReference<IVersionUpdate> mIVersionUpdateReference;

    public static VersionUpdateManager getInstance() {
        if (sVersionUpdateManager == null) {
            sVersionUpdateManager = new VersionUpdateManager();
        }
        return sVersionUpdateManager;
    }

    public void checkVersion(Activity context, boolean showProgress) {
        checkVersionFromNet(context, showProgress, false);
    }

    public void setUpdateOnClickListener(IVersionUpdate iVersionUpdate) {
        mIVersionUpdateReference = new WeakReference<>(iVersionUpdate);
    }



    /**
     * 检测当前版本是否比后台版本高
     *
     * @param context
     * @param upgrade_version
     * @return
     */
    public static boolean isCanUpdateFromNet(Context context, String upgrade_version) {
        if (TextUtils.isEmpty(upgrade_version)) {
            return false;
        }
        upgrade_version = upgrade_version.trim();
        int upVersion = Integer.parseInt(upgrade_version);
        int versionCode = Utils.getVersionCode(context);
        return versionCode < upVersion;
    }


    /**
     * 清除引用
     */
    public void clearReference() {
        if (mIVersionUpdateReference != null) {
            mIVersionUpdateReference.clear();
        }
    }

    public interface IVersionUpdate {
        void onCallBack(boolean isUpdate);
    }

    public void checkVersionFromNet(Context context, boolean silentDownLoad, boolean tip) {
        if (silentDownLoad && !NetUtils.isWifiConnected(context)) {
            return;
        }
        if (com.allenliu.versionchecklib.v2.ui.VersionService.isServiceAlive) {
            ToastUtil.showStaticMessage("正在处理更新,请稍后...");
            return;
        }
        if (mVersionService == null) {
            RetrofitHelper helper = RetrofitHelper.getInstance();
            mVersionService = helper.createService(VersionService.class);
        }
        Call<VersionInfoBean> call = mVersionService.checkVersion(Utils.getVersionCode(Xutils.getContext()) + "");
        AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestUrl(Utils.linkUrl(call.request().url().toString() , JsonUtils.jsonStrToMap(new BaseRequestParams().toJsonStr())))
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(String result) {
                        //return null if you dont want to update application
                        VersionInfoBean info = new Gson().fromJson(result, VersionInfoBean.class);
                        if (info == null || info.result == null || info.result.data == null || TextUtils.isEmpty(info.result.data.upgrade_number)) {
                            return null;
                        }
                        if (!isCanUpdateFromNet(context, info.result.data.upgrade_number)) {
                            if (tip)
                                ToastUtil.showStaticMessage("已经是最新版本了");
                            return null;
                        }
                        if (mIVersionUpdateReference != null && mIVersionUpdateReference.get() != null) {
                            mIVersionUpdateReference.get().onCallBack(true);
                        }
                        UIData data = UIData.create().setDownloadUrl(info.result.data.upgrade_download_url).setTitle("版本升级").setContent(info.result.data.upgrade_desc);
                        return data;
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {

                    }
                })
                .setCustomVersionDialogListener(createVersionDialog())
                .setCustomDownloadingDialogListener(createDownLoadingDialog())
                .setSilentDownload(silentDownLoad)
                .setShowNotification(true)
//                .setDownloadAPKPath("")
                .executeMission(context);
    }

    private CustomVersionDialogListener createVersionDialog() {
        return (context, versionBundle) -> {
            BaseDialog baseDialog = new BaseDialog(context, R.style.dialog_style, R.layout.dialog_version_update_layout);
            TextView textView = baseDialog.findViewById(R.id.desc);
            textView.setText(versionBundle.getContent());
            baseDialog.setCanceledOnTouchOutside(true);
            baseDialog.findViewById(R.id.close).setOnClickListener(v -> {
                baseDialog.cancel();
            });
            return baseDialog;
        };
    }

    private CustomDownloadingDialogListener createDownLoadingDialog() {
        return new CustomDownloadingDialogListener() {
            @Override
            public Dialog getCustomDownloadingDialog(Context context, int progress, UIData versionBundle) {
                BaseDialog baseDialog = new BaseDialog(context, R.style.dialog_style, R.layout.dialog_version_down_loading_layout);
                baseDialog.setCanceledOnTouchOutside(false);
                SeekBar sb = baseDialog.findViewById(R.id.sb);
                sb.setMax(100);
                sb.setClickable(false);
                sb.setEnabled(false);
                sb.setSelected(false);
                sb.setFocusable(false);

                baseDialog.findViewById(R.id.close).setOnClickListener(v -> baseDialog.cancel());
                return baseDialog;
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void updateUI(Dialog dialog, int progress, UIData versionBundle) {
                TextView tvPercentage = dialog.findViewById(R.id.tvPercentage);
                SeekBar sb = dialog.findViewById(R.id.sb);
                sb.setProgress(progress);
                tvPercentage.setText(progress + "%");
            }
        };
    }
}
